package tc.alert.tckejisoc.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tc.alert.tckejisoc.cache.CacheData;
import tc.alert.tckejisoc.domain.SocIp;
import tc.alert.tckejisoc.dto.Constants;
import tc.alert.tckejisoc.service.SocIpService;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/socIp")
@Slf4j
public class SocIpController {

    @Autowired
    private SocIpService socIpService;
    @Autowired
    private CacheData cacheData;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadExcelFile(@RequestParam("file") MultipartFile file) {
        // 验证文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择要上传的文件");
        }

        // 验证文件类型
        if (!"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(file.getContentType())) {
            return ResponseEntity.badRequest().body("仅支持.xlsx格式的Excel文件");
        }

        try {
            List<SocIp> dataList = parseExcelFile(file);
            socIpService.saveBatch(dataList);

            Object o = cacheData.get(Constants.SOCIP);
            if (o != null) {
                List<SocIp> socIps = (List<SocIp>) o;
                socIps.addAll(dataList);
                cacheData.put(Constants.SOCIP, socIps);
            } else {
                cacheData.put(Constants.SOCIP, dataList);
            }


            return ResponseEntity.ok(dataList);
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("文件解析失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误: " + e.getMessage());
        }
    }

    private List<SocIp> parseExcelFile(MultipartFile file) throws IOException {
        List<SocIp> dataList = new ArrayList<>();

        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheet("列表内容");
            if (sheet == null) {
                throw new IOException("Excel文件中缺少Sheet1");
            }

            // 遍历数据行（跳过标题行）
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过标题行

                SocIp data = new SocIp();
                data.setIp(getCellValue(row.getCell(0)));    // 第一列：IP
                data.setContext(getCellValue(row.getCell(3))); // 第四列：备注
                data.setType(1);
                dataList.add(data);
                log.info("ip:" + data.getIp());
            }
        }
        return dataList;
    }

    private String getCellValue(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getLocalDateTimeCellValue().toString();
                } else {
                    return String.valueOf((int) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
